package ru.ognick.coachsystem.core;



import java.util.ArrayList;
import ru.ognick.coachsystem.common.Exercise;
import ru.ognick.coachsystem.common.base.BaseExerciseAdapter;
import ru.ognick.coachsystem.core.CoreExerciseView.TimeStatus;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;

public class CoreExerciseAdapter extends BaseExerciseAdapter<CoreExerciseView> {
    public final String TAG = getClass().getSimpleName();	
	public CoreExerciseAdapter(Context context, 
							   int textViewResourceId, 
							   ArrayList<CoreExerciseView> exercises) {
		super(context, textViewResourceId, exercises);
	}
	

	public CoreExerciseView add(Exercise exercise){
        final CoreExerciseView coreExerciseView = new CoreExerciseView(getContext(), exercise);
        if (exercise.isActivity())
			exercises.add(coreExerciseView);
		coreExerciseView.getChronometer()
			.setOnChronometerTickListener(new OnChronometerTickListener() {
				@Override
				public void onChronometerTick(Chronometer chronometer) {
					TimeStatus status = coreExerciseView.checkTime();
					switch (status) {
					case END:
						playSignal(0);
						Log.d(TAG, "Stop");
						doNext(coreExerciseView);
						break;
					case BEEP:
						playSignal(0);
						Log.d(TAG, "BEEP");
						break;
					default:
						break;
					}
				}
		});
		
		coreExerciseView.getView().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				doSideEffect(coreExerciseView);
			}
		});
		
        notifyDataSetChanged();
        return coreExerciseView;
	}
	
	public SavedState getSavedStates() {
		for (CoreExerciseView coreExerciseView : exercises) {
			SavedState savedState = coreExerciseView.getSavedState();
			if (savedState != null) {
				int position = getPosition(coreExerciseView);
				savedState.setIndex(position);
				return savedState;
			}
		}
		return null; 
	}
	
	public void setSavedStates(SavedState savedState) {
		if (savedState == null)
			return;
		int position = savedState.getIndex();
		CoreExerciseView coreExerciseView = getItem(position);
		coreExerciseView.setSaveState(savedState);
		doSideEffect(coreExerciseView);
	}
	
	
	private void doSideEffect(CoreExerciseView current){
		boolean before = true;
		for (CoreExerciseView coreExerciseView : exercises) {
			if (coreExerciseView.equals(current)) { 
				before = false;
				coreExerciseView.onClick();
			}
			else {
				if (before)
					coreExerciseView.ifBefore();
				else
					coreExerciseView.ifAfter();
			}
		}
	}
	
	private void doNext(CoreExerciseView current){
		int position = getPosition(current);
		try {
			doSideEffect(getItem(position + 1));
		} 
		catch (IndexOutOfBoundsException e) {
			current.ifBefore();
			Log.d(TAG, "Training finish");
		}
	}
	
	private void playSignal(int resourceId){
		
	}
	
	
}
